package com.webcams.core.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.webcams.core.resorts.Resort;


public class AsyncDownloadMapToSd extends AsyncTask<ResortContextCouple, Integer, Resort> {

	private ProgressDialog progress;
	private DownloadMapsManager mapManager;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Resort doInBackground(ResortContextCouple... couples) {
		try {
			ResortContextCouple couple = couples[0];
			URL url = new URL(couple.getResort().getMapDistUrl());

			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			urlConnection.connect();

			File mapFile = couple.getResort().getMapLocalFile(couple.getContext());

			File mapFolder = mapFile.getParentFile();
			if(!mapFolder.exists()){
				mapFolder.mkdirs();
			}


			FileOutputStream fileOutput = new FileOutputStream(mapFile);

			InputStream inputStream = urlConnection.getInputStream();

			int totalSize = urlConnection.getContentLength();
			long downloadedSize = 0;

			if(progress != null) {
				progress.setMax(totalSize);
			}
			
			byte[] buffer = new byte[1024];
			int bufferLength = 0;

			while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				publishProgress((int)downloadedSize);
			}
			fileOutput.close();
			return couple.getResort();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setProgressDialog(ProgressDialog progress) {
		this.progress = progress;
	}
	public void setMapManager(DownloadMapsManager mapManager) {
		this.mapManager = mapManager;
	}

	@Override
	protected void onProgressUpdate(Integer... _progress) {
		if(progress != null) {
			progress.setProgress(_progress[0]);
		}
	}

	@Override
	protected void onPostExecute(Resort r){
		if(progress != null) {
			progress.dismiss();
		}
		if(mapManager != null) {
			mapManager.downloadFinished(r);
		}
	}
}